package net.helix.ui.panels.library;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.tree.TreePath;

import org.jdesktop.swingx.JXTreeTable;

import net.helix.engine.library.LibraryTreeNode;

public class LibraryTreeTableKeyListener implements KeyListener {
	LibraryPane libraryPane;
	public LibraryTreeTableKeyListener(LibraryPane libraryPane){
		super();
		this.libraryPane = libraryPane;
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		JXTreeTable treeTable = libraryPane.getTreeTable();
		
		//  && treeTable.isColumnSelected(0)
		if(treeTable.isEditing() == false){
			if(e.getKeyCode() == KeyEvent.VK_LEFT){
				e.consume();
			}
			if(e.getKeyCode() == KeyEvent.VK_RIGHT){
				e.consume();
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		JXTreeTable treeTable = libraryPane.getTreeTable();
		
		//  && treeTable.isColumnSelected(0)
		if(treeTable.isEditing() == false){
			TreePath selectedPath = treeTable.getPathForRow(treeTable.getSelectedRow());
			if(selectedPath != null && selectedPath.getLastPathComponent() instanceof LibraryTreeNode){
				LibraryTreeNode node = (LibraryTreeNode) selectedPath.getLastPathComponent();
				
				if(e.getKeyCode() == KeyEvent.VK_RIGHT){
					if(node.id == LibraryTreeNode.FOLDER){
						if(treeTable.isExpanded((treeTable.getSelectedRow()))){
							if(node.getChildCount() > 0){
								treeTable.changeSelection(treeTable.getSelectedRow()+1, treeTable.getSelectedColumn(), false, false);
								e.consume();
							}
						}else{
							treeTable.expandRow(treeTable.getSelectedRow());
							
							e.consume();
						}
					}
				}
				if(e.getKeyCode() == KeyEvent.VK_LEFT){
					if(node.id == LibraryTreeNode.FOLDER){
						if(node.getParent() != null){
							if(treeTable.isCollapsed(selectedPath)){
								if(node.getParent() != null && node.getParent().getParent()!= null){
									treeTable.collapsePath(selectedPath.getParentPath());
									
									e.consume();
								}
							}else{
								treeTable.collapsePath(selectedPath);
								
								e.consume();
							}
						}
					}else{
						if(node.getParent() != null && node.getParent().getParent()!= null){
							treeTable.collapsePath(selectedPath.getParentPath());
							
							e.consume();
						}
					}
				}
				
				if(e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN){
					if(node.id != LibraryTreeNode.FOLDER){
						libraryPane.changePreviewPicTo(node);
					}
				}
			}
		}
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		JXTreeTable treeTable = libraryPane.getTreeTable();
		
		//  && treeTable.isColumnSelected(0)
		if(treeTable.isEditing() == false){
			if(e.getKeyCode() == KeyEvent.VK_LEFT){
				e.consume();
			}
			if(e.getKeyCode() == KeyEvent.VK_RIGHT){
				e.consume();
			}
		}
	}

}
